const Service = require("egg").Service;
const fs = require("fs");
const path = require("path");
// qiniu  处理流 await-stream-ready  stream-wormhole md5
const qiniu = require("qiniu");
const awaitWriteStream = require("await-stream-ready").write;
const sendToWormhole = require("stream-wormhole");
// 上传文件的时候 加密
const md5 = require("md5");
const bucket = "my2005a"; //要上传的空间名
const imageUrl = "resource.cuilb.cn/"; // 空间绑定的域名
const accessKey = "CbVl7ZjeRyzGV2DiK9byGpYwRd8dGvcHfRRx8GrN"; //Access Key
const secretKey = "6LQdpf717LumudJsaberSN3251JfBpHtndfR82Yl"; //Secret Key
// 移上是配置项
// 升成一个mac地址 用mac地址换token
const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
// 配置项 空间名字
const options = {
  scope: bucket
};
// 获取协议实例
const putPolicy = new qiniu.rs.PutPolicy(options);
// 获取token
const uploadToken = putPolicy.uploadToken(mac);
//
let config = new qiniu.conf.Config();
//
config.zone = qiniu.zone.Zone_z1;
//set password for 'root'@'localhost'=password('rootroot');

class utilsService extends Service {
  async uploadFiles() {
    const {ctx} = this;
    // 创建一个流
    const stream = await ctx.getFileStream();
    // 获取上传文件的名字
    const filename =
      md5(stream.filename) + path.extname(stream.filename).toLocaleLowerCase();
    // 先上传到本地 ( 临时空间)
    const localFilePath = path.join(__dirname, "../public/uploads", filename);
    // 输出流
    const writeStream = fs.createWriteStream(localFilePath);
    try {
      // 等待流写出成功
      await awaitWriteStream(stream.pipe(writeStream));
      // formUploader 上传的实例 直接可以上传到七牛云
      const formUploader = new qiniu.form_up.FormUploader(config);
      // 上传参数的设置
      const putExtra = new qiniu.form_up.PutExtra();
      const imgSrc = await new Promise((resolve, reject) => {
        // 上传
        formUploader.putFile(
          uploadToken,
          filename,
          localFilePath,
          putExtra,
          (respErr, respBody, respInfo) => {
            if (respErr) {
              reject("");
            }
            if (respInfo.statusCode === 200) {
              resolve(imageUrl + respBody.key);
            } else {
              reject("");
            }
            // 上传之后删除本地文件
            fs.unlinkSync(localFilePath);
          }
        );
      });
      if (imgSrc !== "") {
        return {
          url: imgSrc
        };
      } else {
        return false;
      }
    } catch (err) {
      //如果出现错误，关闭管道
      await sendToWormhole(stream);
      return false;
    }
  }
}

module.exports = utilsService;
